import express from 'express'
import fs from "fs";
import bodyParser from "body-parser";
import multer from "multer";
import * as path from "path";
import {query, start} from "./interface";

const app = express()
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static('public'))
app.use(multer({dest: './upload/'}).any())

// 展示前端页面
app.get('/', (req, res) => {
    res.sendFile('index.html');
})

// 处理post上传文件
app.post('/upload', (req, res) => {
    // 上传的文件在req.files中
    if (req.files && req.files.length > 0) {
        const files = req.files as Express.Multer.File[]
        const file = files[0]
        const pathname = file.path + path.parse(file.originalname).ext
        const filename = path.parse(pathname).base

        console.log("Info:Uploading " + filename)
        fs.rename(file.path, pathname, function (err) {
            if (err) {
                res.json({status: 1, payload: err})
            } else {
                res.json({status: 0, payload: filename})
                start(filename)
            }
        })
    }
})

// 运行结果查询接口
app.get('/query',(req,res)=>{
    const filename=req.query['filename'] as string
    res.json(query(filename))
})

const port=8080
app.listen(port)
console.log("http://localhost:8080")